﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RAP.Framework.Libary.Utils
{
  /// <summary>
  /// 支持分组操作的键值对
  /// </summary>
  public class GroupedDictionary : Hashtable, IGroupedDictionary
  {
    public string GroupField { get; set; }

    /// <summary>
    /// 添加一个项目到当前集合
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    public override void Add(object key, object value)
    {
      var list = this.ToListValue(key, () => new ArrayList());
      list.Add(value);
    }

    /// <summary>
    /// 添加一个项目
    /// </summary>
    /// <param name="value"></param>
    public void Add(object value)
    {
      var key = GroupField.IsNotNullOrEmpty() ? value.GetValue(GroupField) : value.ToString();
      Add(key, value);
    }

    /// <summary>
    /// 添加一个集合到当前集合
    /// </summary>
    /// <param name="values"></param>
    public void Add(IList values)
    {
      if (values.IsNotNullOrEmpty())
      {
        foreach (var item in values)
        {
          Add(item);
        }
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public override object this[object key]
    {
      get => base[key]; set => throw new Exception("无效的操作！");
    }

    /// <summary>
    /// 获取所有分组下的所有项目
    /// </summary>
    /// <returns></returns>
    public IEnumerator AllValues
    {
      get
      {
        foreach (IList list in this.Values)
        {
          foreach (var item in list)
          {
            yield return item;
          }
        }
      }
    }
  }
}
